package com.zywl.web.controller.sys;

import com.zywl.core.beans.*;
import com.zywl.service.*;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.models.PageData;
import com.zywl.utils.models.PageResult;
import com.zywl.utils.utils.*;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.web.controller.base.BaseController;
import com.zywl.web.controller.form.Userform;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UnitService unitService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    @GetMapping("/userListPage")
    public ModelAndView userListPage(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("user/userListPage");
        return mav;
    }

    @PostMapping("/getUserList")
    public PageResult getUserList(HttpServletRequest request, PageData pageData) {
        Map<String, Object> condition = MapUtil.changeMap(request.getParameterMap());
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        PageResult pageResult = null;
        try {
            if(!condition.containsKey("usrStt")){
                condition.put("usrStt","0");
            }
            if(user.getUsrAssociationId() != null){
                condition.put("usrAssociationId",user.getUsrAssociationId());
            }
            pageResult = putToResult(userService.getPageInfo(condition, pageData));
        } catch (Exception e) {
            logger.error("获取人员列表异常", e);
        }
        return pageResult;
    }

    @PostMapping("/passwordReset")
    public AjaxResult passwordReset(Long id, HttpServletRequest request) {
        AjaxResult ar = new AjaxResult();
        try {
            User user = userService.getById(id);
            if (user != null) {
                String userName = user.getUsrName();
                user.setUsrPassword(GenerateCodeUtil.MD5(Constants.DEFAULT_PASSWORD));
                user.setUsrModifyTime(new Date());

                userService.update(user);

                //添加发送短信业务

                ar.success("重置密码成功");
                saveLog(request, LogTypeEnum.USER.getKey(), "人员重置密码-" + userName);
            } else {
                ar.error("重置密码失败，无该人员相关信息，请刷新查看");
            }
        } catch (Exception e) {
            ar.error("重置密码异常", e);
            logger.error("重置密码异常", e);
        }
        return ar;
    }

    @PostMapping("/userDelete")
    public AjaxResult userDelete(Long id, HttpServletRequest request) {
        AjaxResult ar = new AjaxResult();
        try {
            User user = userService.getById(id);
            if (user != null) {
                String userName = user.getUsrName();
//                userService.deleteById(id);
                user.setUsrStt("1");
                user.setUsrModifyTime(new Date());
                userService.update(user);

                ar.success("删除人员成功");
                saveLog(request, LogTypeEnum.USER.getKey(), "人员删除-" + userName);
            } else {
                ar.error("删除人员失败，无该人员相关信息，请刷新查看");
            }
        } catch (Exception e) {
            ar.error("删除人员异常", e);
            logger.error("删除人员异常", e);
        }
        return ar;
    }

    @PostMapping("/userRecover")
    public AjaxResult userRecover(Long id, HttpServletRequest request) {
        AjaxResult ar = new AjaxResult();
        try {
            User user = userService.getById(id);
            if (user != null) {
                String userName = user.getUsrName();
//                userService.deleteById(id);
                user.setUsrStt("0");
                user.setUsrModifyTime(new Date());
                userService.update(user);

                ar.success("恢复人员成功");
                saveLog(request, LogTypeEnum.USER.getKey(), "人员恢复-" + userName);
            } else {
                ar.error("恢复人员失败，无该人员相关信息，请刷新查看");
            }
        } catch (Exception e) {
            ar.error("恢复人员异常", e);
            logger.error("恢复人员异常", e);
        }
        return ar;
    }

    @GetMapping("/userSubmitPage")
    public ModelAndView userSubmitPage(Long id, String selfInfo, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("user/userSubmitPage");
        try {
            mav.addObject("roles",roleService.getListAll("roeId desc"));
            if (id != null) {
                User user = userService.getById(id);
                mav.addObject("user", user);
            }
        } catch (Exception e) {
            logger.error("绑定数据异常", e);
        }
        return mav;
    }

    @PostMapping("/userSubmit")
    public AjaxResult userSubmit(HttpServletRequest request, Userform form) {
        User userSession = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        AjaxResult ar = new AjaxResult();
        if (form != null) {
            User user = null;
            Short roleLevel = null;
            String old = null;
            Date date = new Date();
            try {
                if (form.getUsrId() != null) {
                    user = userService.getById(form.getUsrId());
                    old = user.getUsrName();
                    form.setUsrPassword(user.getUsrPassword());
                    form.setUsrStt(user.getUsrStt());
                    form.setUsrCreateTime(user.getUsrCreateTime());
                } else {
                    user = new User();
                    form.setUsrAssociationId(userSession.getUsrAssociationId());
                    form.setUsrStt("0");
                    form.setUsrCreateTime(date);
                    form.setUsrPassword(GenerateCodeUtil.MD5(Constants.DEFAULT_PASSWORD));
                }

                form.setUsrModifyTime(date);
                BeanUtils.copyProperties(form, user);

                if (StringUtils.isNotEmpty(form.getUsrBirthday()))
                    user.setUsrBirthday(DateUtil.convertStringToDate("yyyy-MM-dd",form.getUsrBirthday()));

                if (form.getUsrRoleId() != null) {
                    Role role = roleService.getById(form.getUsrRoleId());
                    if (role != null) {
                        user.setUsrRoleName(role.getRoeName());
                    }
                }

                if (form.getUsrId() == null) {
                    userService.save(user);
                } else {
                    userService.update(user);
                }
            } catch (Exception e) {
                logger.error("提交人员信息异常", e);
                ar.error("提交人员信息异常", e);
                return ar;
            }

            if (form.getUsrId() == null) {
                saveLog(request, LogTypeEnum.USER.getKey(), "人员新增-" + form.getUsrName());
                ar.success("新增成功");
            } else if (old != null && !old.equals(form.getUsrName())) {
                saveLog(request, LogTypeEnum.USER.getKey(), "人员修改-" + old + "→" + form.getUsrName());
                ar.success("修改成功");
            } else {
                saveLog(request, LogTypeEnum.USER.getKey(), "人员修改-" + form.getUsrName());
                ar.success("修改成功");
            }
        } else {
            ar.error("提交失败，参数为空");
        }
        return ar;
    }

    @GetMapping("/userInfoPage")
    public ModelAndView userInfoPage(Long id, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("user/userInfoPage");
        try {
            User user = null;
            if (id != null) {
                user = userService.getById(id);
                if (user != null) {
                    String headPic = user.getUsrAvatar();
                    if (StringUtils.isNotEmpty(headPic)) {
                        user.setUsrAvatar(IPUtil.getIpPath(request) + headPic);
                    }
                }
            }
            mav.addObject("user", user);
        } catch (Exception e) {
            logger.error("绑定数据异常", e);
        }
        return mav;
    }

    @GetMapping("/changePasswordPage")
    public ModelAndView changePasswordPage(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("user/changePasswordPage");
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        if (user != null) {
            try {
                user = userService.getById(user.getUsrId());
            } catch (Exception e) {
                logger.error("获取人员信息异常");
            }
        }
        mav.addObject("user", user);
        return mav;
    }

    @PostMapping("/changPassword")
    public AjaxResult changPassword(Long usrId, String password, HttpServletRequest request) {
        AjaxResult ar = new AjaxResult();
        try {
            User user = userService.getById(usrId);
            if (user != null) {
                user.setUsrPassword(GenerateCodeUtil.MD5(password));

                userService.update(user);
                ar.success("修改成功");

                saveLog(request, LogTypeEnum.USER.getKey(), "修改登录密码-" + user.getUsrName());
            }
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            ar.error("修改密码异常", e);
        }
        return ar;
    }

    /**
     * 上传头像照片
     * @param request
     * @param multipartRequest
     * @return
     */
    @PostMapping("uploadFile")
    public Map<String,Object> uploadFile(HttpServletRequest request,DefaultMultipartHttpServletRequest multipartRequest){
        CommonsMultipartFile file = (CommonsMultipartFile)multipartRequest.getFile("file");
        Map<String, Object> map = new HashMap();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append(File.separator);
            stringBuffer.append("user");
            stringBuffer.append(File.separator);
            stringBuffer.append(sdf.format(new Date()));
            stringBuffer.append(File.separator);
            stringBuffer.append(System.currentTimeMillis());
            stringBuffer.append(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
            map.put("path",stringBuffer.toString());

            StringBuffer sb=new StringBuffer();
            sb.append("zywl");
            sb.append(stringBuffer.toString());

            String filePath = FileUtil.getFileRealPathForServer(request, sb.toString());
            File newFile = FileUtil.newFile(filePath);
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
